#include "gd32f30x.h"
#include "systick.h"
#include "usart.h"
#include "led.h"
#include "timer.h"
#include "app_nbiot.h"

extern uint8_t update_flag;
extern int udp_socket;
	
int main(void)
{
	char res_buf[128];
	char data_buf[128];
	int times = 0;
	systick_config();	/* 配置系统时钟 */
	LED_init();			/* 初始化 LED */	
	uart_init(115200);	/* 初始化USART0 */
	uart1_init(9600);	/* 初始化USART1 */
	timer5_init(10000,12000);	/* 定时1000ms*/
	printf("Hello world! \r\n");
	
	while(NB_Start())
	{
		u1_printf("AT+NRB\r\n");	/* 重启*/
		while(USART1_RX_NUM == 0) 
			;
		if(USART1_RX_NUM >0)
		{
			printf("NBIoT: %s\r\n",rx1_date_buf);
			USART1_RX_NUM = 0;
		}
	}
	printf("start OK\r\n");

    while(1)
	{
		if(update_flag  == 1)
		{
			update_flag = 0;
			times++;
			LED(times%2);
			sprintf(data_buf,"I am NBIoT , %d.",times);
			NB_Send_data("39.96.35.207", "topic1", data_buf);
			printf("Data send to EMQ...\r\n");
		}
		if(USART1_RX_NUM >0)
		{
			USART1_RX_NUM = 0;
			if(Find_string((char *)rx1_date_buf,"+NSONMI:","\r\n",res_buf)>0)
			{
				u1_printf("AT+NSORF=%d,%d\r\n",udp_socket,res_buf[2]-'0');
			}
			printf("NBIOT: %s\r\n",rx1_date_buf);			
		}
		if(USART_RX_NUM >0)
		{
			USART_RX_NUM = 0;
			u1_printf("%s",rx0_date_buf);			
		}	
    }
}

